package com.pokermadness.listener;

import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener {
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		ServletContext context = session.getServletContext();
		@SuppressWarnings("unchecked")
		HashMap<String, HttpSession> sessions = (HashMap<String, HttpSession>) context.getAttribute("active-sessions");
		sessions.put(session.getId(), session);
		System.out.println("Session created, id: " + session.getId());
		System.out.println("Number of active sessions: " + sessions.size());
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		ServletContext context = session.getServletContext();
		@SuppressWarnings("unchecked")
		HashMap<String, HttpSession> sessions = (HashMap<String, HttpSession>) context.getAttribute("active-sessions");
		if(sessions != null) {
			sessions.remove(session.getId());
		}		
		System.out.println("Session ended, id: " + session.getId());
	}

}
